// V-backend/src/controllers/authController.js
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { Audience, Anchor } = require('../models');

// 生成JWT Token - 修复字段名
const generateToken = (user, userType = 'audience') => {
  const payload = {
    userId: userType === 'audience' ? user.audience_id : user.anchor_id,
    userType: userType
    // 移除认证中间件不期望的字段：username, avatar
  };

  console.log('🔐 生成Token payload:', payload);

  return jwt.sign(payload, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN
  });
};

// 识别账号类型
const identifyAccountType = (username) => {
  const anchorPatterns = [
    /^admin_/,           // admin_开头
    /^anchor_/,          // anchor_开头 (主播)
    /^mgr_/,             // mgr_开头
    /^T\./,              // T.开头 (新增)
    /@staff\.com$/,      // 特定邮箱后缀
  ];

  return anchorPatterns.some(pattern => pattern.test(username)) 
    ? 'anchor' 
    : 'audience';
};

// 统一登录接口
exports.unifiedLogin = async (req, res) => {
  try {
    const { username, password } = req.body;  // 统一使用 username 字段

    // 验证输入
    if (!username || !password) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '账号和密码不能为空'
      });
    }

    // 识别账号类型
    const accountType = identifyAccountType(username);
    console.log(`🔍 识别账号类型: ${username} -> ${accountType}`);

    let user = null;
    let userType = 'audience';

    if (accountType === 'anchor') {
      // 主播/管理员登录逻辑
      console.log(`🔍 在主播表中查找: ${username}`);
      
      // 构建查询条件
      const whereCondition = {};
      
      // 如果是T.开头的账号，按主播名查找
      if (username.startsWith('T.')) {
        whereCondition.anchor_name = username;
      } else {
        // 否则尝试按邮箱查找
        whereCondition.email = username;
      }
      
      user = await Anchor.findOne({
        where: whereCondition
      });
      
      userType = 'anchor';
    } else {
      // 观众登录逻辑
      console.log(`🔍 在观众表中查找: ${username}`);
      
      user = await Audience.findOne({
        where: { 
          email: username 
        }
      });

      if (!user) {
        // 如果邮箱不存在，尝试用用户名查找
        user = await Audience.findOne({
          where: { 
            audience_name: username 
          }
        });
      }
    }

    if (!user) {
      console.log(`❌ 账号不存在: ${username}`);
      return res.status(401).json({
        code: 401,
        success: false,
        message: '账号不存在'
      });
    }

    console.log(`✅ 找到用户: ${user.anchor_name || user.audience_name}`);

    // 验证密码
    let isValidPassword = false;
    if (userType === 'audience') {
      isValidPassword = await user.validatePassword(password);
    } else {
      // Anchor 模型的密码验证 - 修复：确保password字段存在
      if (!user.password) {
        console.log(`❌ 主播账号密码字段缺失: ${username}`);
        return res.status(500).json({
          code: 500,
          success: false,
          message: '账号配置错误，请联系管理员'
        });
      }
      isValidPassword = await bcrypt.compare(password, user.password);
    }

    if (!isValidPassword) {
      console.log(`❌ 密码错误: ${username}`);
      return res.status(401).json({
        code: 401,
        success: false,
        message: '密码错误'
      });
    }

    // 生成token
    const token = generateToken(user, userType);
    console.log('✅ 生成的Token:', token.substring(0, 20) + '...');

    // 返回用户信息（排除密码）
    const userInfo = user.toSafeObject ? user.toSafeObject() : {
      id: user.audience_id || user.anchor_id,
      name: user.audience_name || user.anchor_name,
      email: user.email,
      avatar: user.avatar,
      gender: user.gender,
      createdAt: user.createdAt,
      updatedAt: user.updatedAt
    };

    console.log(`🎯 登录成功: ${userInfo.name}, 类型: ${userType}`);

    res.json({
      code: 200,
      success: true,
      data: {
        token,
        user: userInfo,
        userType: userType,
        accountType: accountType
      },
      message: '登录成功'
    });

  } catch (error) {
    console.error('统一登录错误:', error);
    res.status(500).json({
      code: 500,
      success: false,
      message: '服务器错误，请稍后重试',
      error: error.message
    });
  }
};

// 观众注册
exports.audienceRegister = async (req, res) => {
  try {
    console.log('📝 注册请求体:', req.body);
    console.log('📝 请求头:', req.headers);

    const { audience_name, email, password, gender = 'unknown' } = req.body;

    // 验证输入
    if (!audience_name || !email || !password) {
      console.log('❌ 验证失败:', { audience_name, email, password });
      return res.status(400).json({
        code: 400,
        success: false,
        message: '用户名、邮箱和密码不能为空'
      });
    }

    if (password.length < 6) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '密码长度不能少于6位'
      });
    }

    // 检查邮箱是否已存在
    const existingAudience = await Audience.findOne({
      where: { email: email }
    });

    if (existingAudience) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '邮箱已被注册'
      });
    }

    // 创建观众
    const audience = await Audience.create({
      audience_name: audience_name,
      email: email,
      password: password,
      gender: gender
    });

    // 生成token
    const token = generateToken(audience, 'audience');

    // 返回用户信息（排除密码）
    const userInfo = audience.toSafeObject();

    res.status(201).json({
      code: 201,
      success: true,
      data: {
        token,
        user: userInfo,
        userType: 'audience'
      },
      message: '注册成功'
    });

  } catch (error) {
    console.error('观众注册错误:', error);
    res.status(500).json({
      code: 500,
      success: false,
      message: '注册失败，请稍后重试',
      error: error.message
    });
  }
};

// 主播注册
exports.anchorRegister = async (req, res) => {
  try {
    const { anchor_name, email, password, gender = 'unknown' } = req.body;

    // 验证输入
    if (!anchor_name || !email || !password) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '主播名、邮箱和密码不能为空'
      });
    }

    if (password.length < 6) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '密码长度不能少于6位'
      });
    }

    // 检查邮箱是否已存在
    const existingAnchor = await Anchor.findOne({
      where: { email: email }
    });

    if (existingAnchor) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '邮箱已被注册'
      });
    }

    // 检查主播名是否已存在
    const existingAnchorName = await Anchor.findOne({
      where: { anchor_name: anchor_name }
    });

    if (existingAnchorName) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '主播名已被使用'
      });
    }

    // 创建主播
    const anchor = await Anchor.create({
      anchor_name: anchor_name,
      email: email,
      password: password,
      gender: gender
    });

    // 生成token
    const token = generateToken(anchor, 'anchor');

    // 返回用户信息
    const userInfo = anchor.toSafeObject ? anchor.toSafeObject() : {
      id: anchor.anchor_id,
      name: anchor.anchor_name,
      email: anchor.email,
      avatar: anchor.avatar,
      gender: anchor.gender,
      createdAt: anchor.createdAt,
      updatedAt: anchor.updatedAt
    };

    res.status(201).json({
      code: 201,
      success: true,
      data: {
        token,
        user: userInfo,
        userType: 'anchor'
      },
      message: '主播注册成功'
    });

  } catch (error) {
    console.error('主播注册错误:', error);
    res.status(500).json({
      code: 500,
      success: false,
      message: '注册失败，请稍后重试',
      error: error.message
    });
  }
};

// 获取当前用户信息
exports.getCurrentUser = async (req, res) => {
  try {
    const { userType, userId } = req.user;

    console.log('🔍 获取用户信息:', { userType, userId });

    let user;
    if (userType === 'audience') {
      user = await Audience.findByPk(userId);
    } else if (userType === 'anchor') {
      user = await Anchor.findByPk(userId);
    }

    if (!user) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '用户不存在'
      });
    }

    // 返回用户信息（排除密码）
    const userInfo = user.toSafeObject ? user.toSafeObject() : {
      id: user.audience_id || user.anchor_id,
      name: user.audience_name || user.anchor_name,
      email: user.email,
      avatar: user.avatar,
      gender: user.gender,
      userType: userType
    };

    res.json({
      code: 200,
      success: true,
      data: {
        user: userInfo,
        userType: userType
      },
      message: '获取用户信息成功'
    });

  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({
      code: 500,
      success: false,
      message: '服务器错误'
    });
  }
};

// 保留旧的登录接口用于兼容性
exports.audienceLogin = exports.unifiedLogin;